% analyze_all_cases.m
% 综合分析所有测试案例的优化结果
% 生成论文所需的可视化图表
% 作者: cyx
% 日期: 2025年

clear; clc; close all;

%% 设置
fprintf('=== GMCM 2025 神经网络处理器核内调度优化结果分析 ===\n\n');

% 案例列表
cases = {'Conv_Case0', 'Conv_Case1', 'Matmul_Case0', 'Matmul_Case1', ...
         'FlashAttention_Case0', 'FlashAttention_Case1'};

% 颜色设置（高对比度配色方案）
colors = [
    0.0 0.2 0.8;    % Conv_Case0 - 深蓝色
    0.8 0.0 0.0;    % Conv_Case1 - 深红色  
    0.0 0.6 0.0;    % Matmul_Case0 - 深绿色
    1.0 0.5 0.0;    % Matmul_Case1 - 橙色
    0.6 0.0 0.6;    % FlashAttention_Case0 - 深紫色
    0.0 0.6 0.6;    % FlashAttention_Case1 - 深青色
];

%% 1. 数据准备
fprintf('1. 准备所有案例数据...\n');

%% 2. 读取所有案例的汇总数据
fprintf('2. 读取所有案例的汇总数据...\n');
summary_data = {};

for i = 1:length(cases)
    case_name = cases{i};
    summary_file = sprintf('result/%s/%s_summary.txt', case_name, case_name);
    
    if exist(summary_file, 'file')
        summary = parse_summary_file(summary_file);
        summary.case_name = case_name;
        summary_data{i} = summary;
        fprintf('   ✓ %s: %d节点, %.2f%%改进\n', case_name, summary.graph_size, summary.improvement_percent);
    else
        fprintf('   ❌ 未找到: %s\n', summary_file);
    end
end

%% 3. 读取收敛曲线数据
fprintf('3. 读取收敛曲线数据...\n');
convergence_data = {};

for i = 1:length(cases)
    case_name = cases{i};
    conv_file = sprintf('result/%s/%s_overall_convergence.csv', case_name, case_name);
    
    if exist(conv_file, 'file')
        data = readtable(conv_file);
        convergence_data{i} = data;
        fprintf('   ✓ %s: %d个收敛点\n', case_name, height(data));
    else
        fprintf('   ❌ 未找到: %s\n', conv_file);
    end
end

%% 4. 生成论文图表
fprintf('4. 生成可视化图表...\n');

% 图表1: 所有案例的收敛曲线对比
figure('Position', [100, 100, 1200, 800], 'Color', 'white');
subplot(2, 2, 1);
set(gca, 'Color', 'white', 'XColor', 'black', 'YColor', 'black', 'Box', 'on', 'LineWidth', 1);
hold on;
for i = 1:length(convergence_data)
    if ~isempty(convergence_data{i})
        data = convergence_data{i};
        % 标准化处理（相对改进百分比）
        initial_score = data.score(1);
        normalized_score = (data.score / initial_score) * 100;
        
        plot(1:height(data), normalized_score, 'LineWidth', 1.0, 'Color', colors(i,:), ...
             'DisplayName', strrep(cases{i}, '_', '\_'));
    end
end
xlabel('优化步骤', 'Color', 'black');
ylabel('相对性能 (%)', 'Color', 'black');
title('(a) 所有案例收敛曲线对比', 'Color', 'black');
legend('Location', 'best', 'EdgeColor', [0.5 0.5 0.5], 'TextColor', 'black', 'Color', 'white');
grid on;
set(gca, 'GridColor', 'black', 'GridAlpha', 0.3, 'XColor', 'black', 'YColor', 'black');

% 图表2: 优化效果对比（柱状图）
subplot(2, 2, 2);
set(gca, 'Color', 'white', 'XColor', 'black', 'YColor', 'black', 'Box', 'on', 'LineWidth', 1);
improvement_rates = [];
case_labels = {};
for i = 1:length(summary_data)
    if ~isempty(summary_data{i})
        improvement_rates = [improvement_rates; summary_data{i}.improvement_percent];
        case_labels{end+1} = strrep(summary_data{i}.case_name, '_', '\_');
    end
end

bar(improvement_rates, 'FaceColor', 'flat', 'CData', colors(1:length(improvement_rates),:), 'EdgeColor', 'black', 'LineWidth', 1);
set(gca, 'XTickLabel', case_labels, 'XColor', 'black', 'YColor', 'black');
xtickangle(45);
ylabel('内存占用改进率 (%)', 'Color', 'black');
title('(b) 各案例优化效果对比', 'Color', 'black');
grid on;
set(gca, 'GridColor', 'black', 'GridAlpha', 0.3, 'XColor', 'black', 'YColor', 'black');

% 图表3: 图规模 vs 优化效果
subplot(2, 2, 3);
set(gca, 'Color', 'white', 'XColor', 'black', 'YColor', 'black', 'Box', 'on', 'LineWidth', 1);
graph_sizes = [];
for i = 1:length(summary_data)
    if ~isempty(summary_data{i})
        graph_sizes = [graph_sizes; summary_data{i}.graph_size];
    end
end

scatter(graph_sizes, improvement_rates, 120, colors(1:length(improvement_rates),:), 'filled', 'MarkerEdgeColor', 'black', 'LineWidth', 1);
xlabel('图规模 (节点数)', 'Color', 'black');
ylabel('优化改进率 (%)', 'Color', 'black');
title('(c) 图规模与优化效果关系', 'Color', 'black');
grid on;
set(gca, 'GridColor', 'black', 'GridAlpha', 0.3, 'XColor', 'black', 'YColor', 'black');

% 添加案例标签
for i = 1:length(case_labels)
    text(graph_sizes(i), improvement_rates(i), sprintf('  %s', case_labels{i}), ...
         'FontSize', 8, 'HorizontalAlignment', 'left', 'Color', 'black', 'FontWeight', 'bold', 'BackgroundColor', [1 1 0.9], 'EdgeColor', [0.5 0.5 0.5]);
end

% 图表4: 两阶段算法贡献分析
subplot(2, 2, 4);
set(gca, 'Color', 'white', 'XColor', 'black', 'YColor', 'black', 'Box', 'on', 'LineWidth', 1);
phase1_contributions = [];
phase2_contributions = [];

for i = 1:length(summary_data)
    if ~isempty(summary_data{i})
        s = summary_data{i};
        total_improvement = s.initial_score - s.final_score;
        phase1_improvement = s.initial_score - s.phase1_score;
        phase2_improvement = s.phase1_score - s.final_score;
        
        phase1_contributions = [phase1_contributions; phase1_improvement/total_improvement*100];
        phase2_contributions = [phase2_contributions; phase2_improvement/total_improvement*100];
    end
end

x_pos = 1:length(case_labels);
stacked_data = [phase1_contributions, phase2_contributions];
b = bar(x_pos, stacked_data, 'stacked', 'EdgeColor', 'black', 'LineWidth', 1);
b(1).FaceColor = [0.2 0.4 0.8];  % 阶段1颜色
b(2).FaceColor = [0.8 0.4 0.2];  % 阶段2颜色
set(gca, 'XTickLabel', case_labels, 'XColor', 'black', 'YColor', 'black');
xtickangle(45);
ylabel('相对贡献 (%)', 'Color', 'black');
title('(d) 两阶段算法贡献分析', 'Color', 'black');
legend({'阶段1 (随机搜索)', '阶段2 (局部搜索)'}, 'Location', 'best', 'EdgeColor', [0.5 0.5 0.5], 'TextColor', 'black', 'Color', 'white');
grid on;
set(gca, 'GridColor', 'black', 'GridAlpha', 0.3, 'XColor', 'black', 'YColor', 'black');

sgtitle('神经网络处理器核内调度优化算法性能分析', 'FontSize', 16, 'FontWeight', 'bold', 'Color', 'black');

%% 5. 保存图表
fprintf('5. 保存分析结果...\n');
% 确保白色背景和黑色边框
set(gcf, 'Color', 'white', 'InvertHardcopy', 'off');
% 设置所有子图的背景和边框
for i = 1:4
    subplot(2, 2, i);
    set(gca, 'Color', 'white', 'XColor', 'black', 'YColor', 'black', 'Box', 'on', 'LineWidth', 1);
end
print(gcf, 'comprehensive_analysis.png', '-dpng', '-r300');
saveas(gcf, 'comprehensive_analysis.fig');
fprintf('   ✓ 图表已保存: comprehensive_analysis.png/fig\n');

%% 6. 生成详细报告
fprintf('6. 生成详细分析报告...\n');
generate_detailed_report(summary_data, convergence_data);

fprintf('\n=== 分析完成 ===\n');

%% 辅助函数
function summary = parse_summary_file(filename)
    % 解析summary文件
    fid = fopen(filename, 'r');
    content = textscan(fid, '%s', 'Delimiter', '\n', 'WhiteSpace', '');
    fclose(fid);
    lines = content{1};
    
    summary = struct();
    for i = 1:length(lines)
        line = lines{i};
        if contains(line, 'Graph Size:')
            tokens = regexp(line, 'Graph Size: (\d+)', 'tokens');
            if ~isempty(tokens)
                summary.graph_size = str2double(tokens{1}{1});
            end
        elseif contains(line, 'Initial V_stay:')
            tokens = regexp(line, 'Initial V_stay: (\d+)', 'tokens');
            if ~isempty(tokens)
                summary.initial_score = str2double(tokens{1}{1});
            end
        elseif contains(line, 'Phase 1 V_stay:')
            tokens = regexp(line, 'Phase 1 V_stay: (\d+)', 'tokens');
            if ~isempty(tokens)
                summary.phase1_score = str2double(tokens{1}{1});
            end
        elseif contains(line, 'Final V_stay:')
            tokens = regexp(line, 'Final V_stay: (\d+)', 'tokens');
            if ~isempty(tokens)
                summary.final_score = str2double(tokens{1}{1});
            end
        elseif contains(line, 'Improvement:')
            tokens = regexp(line, 'Improvement: \d+ \((.+)%\)', 'tokens');
            if ~isempty(tokens)
                summary.improvement_percent = str2double(tokens{1}{1});
            end
        end
    end
end

function generate_detailed_report(summary_data, convergence_data)
    % 生成详细分析报告
    report_file = 'detailed_analysis_report.txt';
    fid = fopen(report_file, 'w');
    
    fprintf(fid, '=== 神经网络处理器核内调度优化算法 - 详细分析报告 ===\n');
    fprintf(fid, '生成时间: %s\n\n', datestr(now));
    
    fprintf(fid, '1. 实验概述\n');
    fprintf(fid, '   测试案例数量: %d\n', length(summary_data));
    fprintf(fid, '   算法类型: 两阶段混合优化 (随机搜索 + 迭代局部搜索)\n');
    fprintf(fid, '   优化目标: 最小化内存峰值占用 (V_stay)\n\n');
    
    fprintf(fid, '2. 各案例详细结果\n');
    for i = 1:length(summary_data)
        if ~isempty(summary_data{i})
            s = summary_data{i};
            fprintf(fid, '   案例: %s\n', s.case_name);
            fprintf(fid, '     图规模: %d 节点\n', s.graph_size);
            fprintf(fid, '     初始V_stay: %d\n', s.initial_score);
            fprintf(fid, '     阶段1后V_stay: %d (改进 %.2f%%)\n', s.phase1_score, ...
                    100*(s.initial_score-s.phase1_score)/s.initial_score);
            fprintf(fid, '     最终V_stay: %d (总改进 %.2f%%)\n', s.final_score, s.improvement_percent);
            fprintf(fid, '     内存节省: %d 单位\n\n', s.initial_score - s.final_score);
        end
    end
    
    fprintf(fid, '3. 算法性能分析\n');
    improvements = [];
    sizes = [];
    for i = 1:length(summary_data)
        if ~isempty(summary_data{i})
            improvements = [improvements; summary_data{i}.improvement_percent];
            sizes = [sizes; summary_data{i}.graph_size];
        end
    end
    
    fprintf(fid, '   平均改进率: %.2f%%\n', mean(improvements));
    fprintf(fid, '   最佳改进率: %.2f%% (%s)\n', max(improvements), summary_data{improvements==max(improvements)}.case_name);
    fprintf(fid, '   改进率标准差: %.2f%%\n', std(improvements));
    fprintf(fid, '   图规模范围: %d - %d 节点\n', min(sizes), max(sizes));
    
    fclose(fid);
    fprintf('   ✓ 详细报告已生成: %s\n', report_file);
end
